package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.model.entity.RoomInfo;
import com.atguigu.lease.web.app.mapper.ApartmentInfoMapper;
import com.atguigu.lease.web.app.mapper.RoomInfoMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.service.RoomInfoService;
import com.atguigu.lease.web.app.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.app.vo.room.RoomDetailVo;
import com.atguigu.lease.web.app.vo.room.RoomItemVo;
import com.atguigu.lease.web.app.vo.room.RoomQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo> implements RoomInfoService {

    private final RoomInfoMapper roomInfoMapper;

    private final ApartmentInfoMapper apartmentInfoMapper;

    private final BrowsingHistoryService browsingHistoryService;

    @Override
    public IPage<RoomItemVo> pageRoomItemVoByQuery(Page<RoomItemVo> page, RoomQueryVo queryVo) {
        return roomInfoMapper.pageRoomItemVoByQuery(page,queryVo);
    }

    @Override
    public RoomDetailVo getRoomDetailVoByRoomId(Long id) {
        RoomDetailVo roomDetailVo = roomInfoMapper.getRoomDetailVoByRoomId(id);
        Long total = roomInfoMapper.getAgreementByRoomId(id);
        roomDetailVo.setIsCheckIn(total > 0);

        ApartmentItemVo apartmentItemVo = apartmentInfoMapper.getApartmentItemVoByRoomId(id);
        roomDetailVo.setApartmentItemVo(apartmentItemVo);

        // 测试@Async
        System.out.println("getRoomDetailVoByRoomId(): ===  " + Thread.currentThread().getName());

        // 在用户浏览房间详情时,应保存浏览记录 (异步完成 --> 查询方法没有必要等到save完毕之后才返回结果)
         /*
            获取userId的细节:
                1. 用户登录成功后,在AuthenticationInterceptor的preHandle()中获取token的负载信息，从而拿到当前登录用户userId,userName
                2. 同时，将当前登录的用户信息存入ThreadLocal中
                3. 所以，这里就可以直接从ThreadLocal中获取userId
          */
        browsingHistoryService.saveHistory(LoginUserContext.getLoginUser().getUserId(),id);
        return roomDetailVo;
    }

    /**
     * 根据公寓ID分页查询房间信息
     * @param page
     * @param apartmentId
     * @return
     */
    @Override
    public IPage<RoomItemVo> pageItemByApartmentId(Page<RoomItemVo> page, Long apartmentId) {
        return roomInfoMapper.pageItemByApartmentId(page,apartmentId);
    }


}




